package com.ytjj.quartz.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.github.pagehelper.util.StringUtil;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.PropertiesReader;
import com.kuaidi100.sdk.utils.SignUtils;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.SendMsg;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.exception.GlobalExceptionHandler;
import com.ytjj.common.model.request.AliPayOrderSyncRequest;
import com.ytjj.common.model.response.OrdersPayResponse;
import com.ytjj.common.service.AlipayService;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.users.client.OrderClient;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.quartz.config.SupplyApiConfig;
import com.ytjj.quartz.constants.ExpireTimeConstant;
import com.ytjj.quartz.constants.IsPayConstant;
import com.ytjj.quartz.dao.*;
import com.ytjj.quartz.enums.*;
import com.ytjj.quartz.model.MessageRecord;
import com.ytjj.quartz.model.*;
import com.ytjj.quartz.model.YxReturnGoods;
import com.ytjj.quartz.model.dto.ExpressRecordDto;
import com.ytjj.quartz.model.dto.RepeatPayOrderRecordDto;
import com.ytjj.quartz.utils.ExpressDicUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 *
 * @version 1.0
 *
 */
@Service
@Slf4j
@RefreshScope
public class OrdersService {

    @Resource
    private OrdersDao ordersDao;

    @Resource
    private AlipayService alipayService;

    @Resource
    private OrdersPayMapper ordersPayMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private MallClient mallClient;

    @Resource
    private ExpressOrdersMapper expressOrdersMapper;

    @Resource
    private OrdersInfoMapper ordersInfoMapper;

    @Resource
    private BankerOrderDao bankerOrderDao;

    @Resource
    private OrderExceptionMapper orderExceptionMapper;

    @Resource
    private BankerMapper bankerMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private BankerOrderMapper bankerOrderMapper;

    @Resource
    private SysConfigUtil sysConfigUtil;

    @Resource
    private OrdersInfoDao ordersInfoDao;
    @Resource
    private DynamicMapper dynamicMapper;

    @Resource
    private RedisService redisService;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private UsersClient usersClient;
    @Resource
    private OrderClient orderClient;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductSpecMapper productSpecMapper;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;

    @Resource
    private MessageRecordDao messageRecordDao;
    @Value("${pushGtNum:10}")
    private String pushGtNum;
    @Value("${expressStatus.threshold:72}")
    private String expressStatusThreshold;

    @Value("${brokerageRatio:1.6}")
    private String brokerageRatio;
    /**
     * 发货发送短信开关 1-发送 0-不发送
     */
    @Value("${expressSmsFlag:1}")
    private String expressSmsFlag;

    @Value("${unfilledOrderDay:30}")
    private Integer unfilledOrderDay;

    /**
     * 是否开启检查订单飞书通知 true 开启 false关闭
     */
    @Value("${checkOrderFeishu:false}")
    private boolean checkOrderFeishu;

    @Resource
    private HelpWorkInfoDao helpWorkInfoDao;


    @Transactional(rollbackFor = Exception.class)
    public void updateWxAppOrdersStatus() {
        List<OrdersPay> payList = ordersDao.getWxAppOrdersPayList();
        payList.stream().forEach(item -> {
            try {
                String no = item.getResOrderNo();
                if ("HFTX".equals(item.getTradeType())){
                    no =item.getTransactionId();
                }
                Map<String, String> map = mallClient.wxAppOrderQuery(no, item.getTradeType());
                log.info("订单查询结果：{}", JSONObject.toJSONString(map));
                if (!"UPAY".equals(item.getTradeType()) && !"HFTX".equals(item.getTradeType())){
                    if ("SUCCESS".equals(map.get("trade_state"))) {
                        map.put("trade_type", item.getTradeType());
                        mallClient.updateOrdersPay(map);
                    } else if ("USERPAYING".equals(map.get("trade_state"))) {

                    } else if ("CLOSED".equals("trade_state")) {

                    } else {
                        // 失败或者不支付
                        item.setPayType(PayPayTypeEnums.FAIL.getType());
                        item.setResText(JSONObject.toJSONString(map));
                        ordersPayMapper.updateByPrimaryKeyWithBLOBs(item);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询订单发生异常：e:{}", GlobalExceptionHandler.getExceptionToString(e));
            }
        });
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateISVWxAppOrdersStatus() {
        List<OrdersPay> payList = ordersDao.getISVWxAppOrdersPayList();
        payList.stream().forEach(item -> {
            try {
                Map<String, String> map = orderClient.wxAppOrderQuery(item.getResOrderNo(), item.getTradeType());
                log.debug("微信支付服务商模式订单查询结果：{}", JSONObject.toJSONString(map));
                if ("SUCCESS".equals(map.get("trade_state"))) {
                    map.put("trade_type", item.getTradeType());
                    mallClient.updateOrdersPay(map);
                } else if ("USERPAYING".equals(map.get("trade_state"))) {
                } else {
                    // 失败或者不支付
                    item.setPayType(PayPayTypeEnums.FAIL.getType());
                    item.setResText(JSONObject.toJSONString(map));
                    ordersPayMapper.updateByPrimaryKeyWithBLOBs(item);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询订单发生异常：e:{}", GlobalExceptionHandler.getExceptionToString(e));
            }
        });
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateOrdersStatus() {
        List<Orders> ordersList = ordersDao.getOrdersList();
        ordersList.stream()
                .forEach(item -> {
                    OrdersExample example = new OrdersExample();
                    example.createCriteria()
                            .andIdEqualTo(item.getId())
                            .andOrderStatusEqualTo(OrderStatusEnums.OBLIGATION.getValue());
                    item.setOrderStatus(OrderStatusEnums.CLOSED.getValue());
                    item.setOrderRemarks("订单超时未支付,已取消");
                    ordersMapper.updateByExampleSelective(item, example);

                    // 修改订单明细状态
                    OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
                    ordersInfoExample.createCriteria().andOrderIdEqualTo(item.getId());
                    List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
                    ordersInfos.stream().forEach(oi -> {
                        OrdersInfo ordersInfo = new OrdersInfo();
                        ordersInfo.setId(oi.getId());
                        ordersInfo.setOrderinfoStatus(OrderStatusEnums.CLOSED.getValue());
                        ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
                        // 加库存 减销量
                        //todo 目前订单购买的商品数量只有1
                        Integer sum = 1;
                        Product product = productMapper.selectByPrimaryKey(oi.getProductId());
                        if (product.getIsZeroProduct() != null && product.getIsZeroProduct() == 1 && product.getStockEvaluation() != null && product.getStockEvaluation() > 0) {
                            product.setStockEvaluation(product.getStockEvaluation() + sum);
                        } else {
                            product.setStock(Optional.ofNullable(product.getStock()).orElse(0) + sum);
                        }
                        try {
                            helpWorkInfoDao.updasteStatu(ordersInfo.getId());
                        } catch (Exception e) {
                            log.error("===e==={}", e);
                            log.error("===更新助力单状态异常==={}", ordersInfo.getId());
                        }
                        productMapper.updateByPrimaryKeySelective(product);
                        ProductSpec productSpec = productSpecMapper.selectByPrimaryKey(oi.getProductSpecId());
                        productSpec.setBuySum(Optional.ofNullable(productSpec.getBuySum()).orElse(0) - sum);
                        productSpec.setStock(Optional.ofNullable(productSpec.getStock()).orElse(0) + sum);
                        productSpecMapper.updateByPrimaryKeySelective(productSpec);
                    });
                });
    }

    @Transactional(rollbackFor = Exception.class)
    public void ordersStatus() {
        List<Orders> ordersList = ordersDao.getOrders();
        long time = 60 * 60 * 1000;
        if (ordersList.size() > 0) {
            ordersList.stream()
                    .forEach(item -> {
                                if (messageRecordDao.selectMessage(item.getTel(), 1) <= Integer.parseInt(pushGtNum)) {
                                    MessageRecord messageRecord = new MessageRecord();
                                    messageRecord.setUPhone(item.getTel());
                                    messageRecord.setBizNo(item.getOrderNo());
                                    push(JSONObject.toJSONString(messageRecord), time);
                                }
                            }
                    );
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void MessageStatus() {
        messageRecordDao.updateMessage();
    }

    @Transactional(rollbackFor = Exception.class)
    public void HelpStatus() {
        messageRecordDao.updateHelp();
    }

    private void push(String json, long delayTimes) {
        // 给延迟队列发送消息
        rabbitTemplate.convertAndSend(QueueConstants.ORDER_STATE_TWO, json, message -> {
            //给消息设置延迟毫秒值
            message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
            return message;
        });
    }


    @Transactional(rollbackFor = Exception.class)
    public void updateAliPayAppOrdersStatus(String orderNo) {
        List<OrdersPay> payList = ordersDao.getAliPayAppOrdersPayList(orderNo);
        payList.stream().forEach(item -> {
            try {
                AlipayTradeQueryResponse response = alipayService.AliPayAppOrderQueryByCert(item.getResOrderNo(), "");
                log.info("getOutTradeNo={}", response.getOutTradeNo());
                if ("10000".equals(response.getCode())) {
                    log.info("response.getMsg()={}", response.getMsg());
                    if ("Success".equalsIgnoreCase(response.getMsg())) {
                        String state = response.getTradeStatus();
                        log.info("response.getTradeStatus()={}", response.getTradeStatus());
                        if ("TRADE_SUCCESS".equals(state)) {
                            // 成功
                            mallClient.updateAliPayOrdersPay(response);
                        }
                        if ("TRADE_CLOSED".equals(state)) {
                            // 失败或者不支付
                            item.setPayType(PayPayTypeEnums.FAIL.getType());
                            item.setResText(JSONObject.toJSONString(response));
                            ordersPayMapper.updateByPrimaryKeyWithBLOBs(item);
                        }
                    } else {
                        log.info("查询订单失败----------->");
                    }
                } else {
                    if ("40004".equals(response.getCode())) {
                        // 订单不存在
                        item.setPayType(PayPayTypeEnums.FAIL.getType());
                        item.setResText(JSONObject.toJSONString(response));
                        ordersPayMapper.updateByPrimaryKeyWithBLOBs(item);
                    } else {
                        // 查询失败
                        log.info("订单查询失败：outOrderNo:{}", item.getResOrderNo());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询订单发生异常：e:{}", GlobalExceptionHandler.getExceptionToString(e));
            }
        });
    }

    //暂未使用
//    public void updateExpressOrders() {
//        ExpressOrdersExample expressOrdersExample = new ExpressOrdersExample();
//        expressOrdersExample.createCriteria()
//                .andIsCheckEqualTo((byte) 0).andInvalidFlagEqualTo(ExpressOrderInvalidFlagEnums.YES.getValue());
//        List<ExpressOrders> expressOrdersList = expressOrdersMapper.selectExpressOrderList();
//        try {
//            //已发货发送通知
//            List<String> expressNos = expressOrdersList.stream().map(ExpressOrders::getExpressEno).collect(Collectors.toList());
//            List<OrderExpressNoAndOrderNoResponse> orderNoList = ordersDao.queryOrderNoByExpressNo(expressNos);
//            long time = 60 * 60 * 1000;
//            for (ExpressOrders eo : expressOrdersList) {
//                if (!eo.getExpressEno().isEmpty()) {
//                    //快递订单号长度>0,生产到队列
//                    if (messageRecordDao.selectMessage(eo.getPhone(), 2) <= Integer.parseInt(pushGtNum)) {
//                        List<OrderExpressNoAndOrderNoResponse> orderNo = orderNoList.stream().filter(s -> s.getExpressNo().equals(eo.getExpressEno())).collect(Collectors.toList());
//                        if (!CollectionUtils.isEmpty(orderNo)) {
//                            MessageRecord messageRecord = new MessageRecord();
//                            messageRecord.setBizNo(orderNo.get(0).getOrderNo());
//                            messageRecord.setUPhone(eo.getPhone());
//                            log.info("已发货已经在极光通知了------》");
//                            pushOne(JSONObject.toJSONString(messageRecord), time);
//                        }
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("消息队列异常");
//        }
//        handleOrderExpressInfo(expressOrdersList);
//    }

    /**
     * 3天以内的加快频率扫描快递信息
     */
//    public void updateExpressOrdersStageOne() {
//        LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
//        ldt = ldt.plusDays(-3);
//        Date date = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
//
//        ExpressOrdersExample expressOrdersExample = new ExpressOrdersExample();
//        expressOrdersExample.createCriteria()
//                .andIsCheckEqualTo((byte) 0)
//                .andInvalidFlagEqualTo(ExpressOrderInvalidFlagEnums.YES.getValue())
//                .andCreateTimeGreaterThanOrEqualTo(date);
//        List<ExpressOrders> expressOrdersList = expressOrdersMapper.selectByExample(expressOrdersExample);
//        handleOrderExpressInfo(expressOrdersList);
//    }

//    private void handleOrderExpressInfo(List<ExpressOrders> expressOrdersList) {
//        expressOrdersList.stream().forEach(item -> {
//            QueryTrack queryTrack = new QueryTrack();
//            QueryTrackReq queryTrackReq = new QueryTrackReq();
//            QueryTrackParam queryTrackParam = new QueryTrackParam();
//            queryTrackParam.setCom(item.getCompanyNo());
//            queryTrackParam.setNum(item.getExpressEno());
//            queryTrackParam.setPhone(item.getPhone());
//            queryTrackReq.setParam(queryTrackParam);
//            queryTrackReq.setCustomer(PropertiesReader.get("customer"));
//            queryTrackReq.setSign(SignUtils.sign(new Gson().toJson(queryTrackParam) + PropertiesReader.get("key") + PropertiesReader.get("customer")));
//            QueryTrackResp resp = queryTrack.queryTrack(queryTrackReq);
//            log.debug("快递100 手动查询结果：{}", JSONObject.toJSONString(resp));
//            if ("200".equals(resp.getStatus())) {
//                // 查询成功
//                item.setMessage(resp.getMessage());
//                item.setResText(JSONObject.toJSONString(resp));
//                item.setInfoText(JSONObject.toJSONString(resp.getData()));
//                item.setIsCheck(Byte.valueOf(resp.getIscheck()));
//                item.setStatus(Byte.valueOf(resp.getState()));
//                item.setExpressStatus(resp.getStatus());
//                item.setUpdateTime(new Date());
//                expressOrdersMapper.updateByPrimaryKeySelective(item);
//                if ("3".equals(resp.getState())) {
//                    try {
//                        // 已签收
//                        if (messageRecordDao.selectMessage(item.getPhone(), 3) <= Integer.parseInt(pushGtNum)) {
//                            long time = 60 * 60 * 1000;
//                            MessageRecord messageRecord = new MessageRecord();
//                            messageRecord.setUPhone(item.getPhone());
//                            messageRecord.setBizNo(item.getExpressEno());
//                            pushTwo(JSONObject.toJSONString(messageRecord), time);
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        log.error("消息队列异常");
//                    }
//                    OrdersInfoExample updateOrdersInfoExample = new OrdersInfoExample();
//                    updateOrdersInfoExample.createCriteria()
//                            .andExpressNoEqualTo(item.getExpressEno());
//                    OrdersInfo ordersInfo = new OrdersInfo();
//                    ordersInfo.setUpdateTime(new Date());
//                    ordersInfo.setReceiveTime(new Date());
//                    ordersInfo.setReceiveStatus((byte) 1);
//                    ordersInfo.setOrderinfoStatus("3");
//                    ordersInfoMapper.updateOrderStatusByExpressEno(item.getExpressEno());
//
//                    // 判断订单下面的订单是否已经全部完成
//                    OrdersInfoExample infoExample = new OrdersInfoExample();
//                    infoExample.createCriteria()
//                            .andExpressNoEqualTo(item.getExpressEno());
//                    List<OrdersInfo> list = ordersInfoMapper.selectByExample(infoExample);
//                    List<Integer> ordersIdList = list.stream().map(chileItem -> chileItem.getOrderId())
//                            .distinct()
//                            .collect(Collectors.toList());
//                    ordersIdList.stream().forEach(chileItem -> {
//                        OrdersInfoExample example = new OrdersInfoExample();
//                        example.createCriteria()
//                                .andOrderIdEqualTo(chileItem)
//                                .andReceiveStatusEqualTo((byte) 0);
//                        Long count = ordersInfoMapper.countByExample(example);
//                        if (count.intValue() == 0) {
//                            // 订单已完成
//                            Orders orders = ordersMapper.selectByPrimaryKey(chileItem);
//                            if (!orders.getOrderStatus().equals("4") && !orders.getOrderStatus().equals("5") && !orders.getOrderStatus().equals("6")) {
//                                orders.setOrderStatus("3");
//                                ordersMapper.updateByPrimaryKeySelective(orders);
//                            }
//                        }
//                    });
//                } else {
//                    boolean checkResult = checkExpressStatusUpdateDuration(item.getInfoText());
//                    if (checkResult) {
//                        BankerOrderExample bankerOrderExample = new BankerOrderExample();
//                        bankerOrderExample.createCriteria().andExpressNoEqualTo(item.getExpressEno());
//                        List<BankerOrder> bankerOrders = bankerOrderMapper.selectByExample(bankerOrderExample);
//                        if (!CollectionUtils.isEmpty(bankerOrders)) {
//                            BankerOrder bankerOrder = bankerOrders.get(0);
//                            saveExceptionOrder(bankerOrder, "快递停留过长");
//                            bankerOrder.setStatus((byte) 2);
//                            bankerOrderMapper.updateByPrimaryKey(bankerOrder);
//                        }
//                    } else {
//                        BankerOrderExample bankerOrderExample = new BankerOrderExample();
//                        bankerOrderExample.createCriteria().andExpressNoEqualTo(item.getExpressEno());
//                        List<BankerOrder> bankerOrders = bankerOrderMapper.selectByExample(bankerOrderExample);
//                        if (CollectionUtils.isEmpty(bankerOrders)) {
//                            return;
//                        }
//                        OrderException orderException = null;
//                        orderException = orderExceptionMapper.selectById(bankerOrders.get(0).getId());
//                        if (null != orderException) {
//                            orderException.setUpdateTime(new Date());
//                            orderException.setStatus((byte) 2);
//                            orderException.setExceptionDesc("异常快递已经处理");
//                            //更新物流记录 jiangkang 2021-10-09
//                            orderException.setExpressRecord(item.getInfoText());
//                            orderExceptionMapper.updateByPrimaryKeySelective(orderException);
//                        }
//                    }
//                }
//            }
//
//        });
//    }


    /**
     * 检查快递最新记录的时间是否超过了n小时
     *
     * @param expressRecord 快递流水记录
     */
    private boolean checkExpressStatusUpdateDuration(String expressRecord) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(expressRecord)) {
            return false;
        }
        List<ExpressRecordDto> dtos = JSONArray.parseArray(expressRecord, ExpressRecordDto.class);
        if (CollectionUtils.isEmpty(dtos)) {
            return false;
        }
        //升序
        dtos = dtos.stream().sorted(Comparator.comparing(ExpressRecordDto::getFtime)).collect(Collectors.toList());
        ExpressRecordDto dto = dtos.get(dtos.size() - 1);
        String ftime = dto.getFtime();
        if (org.apache.commons.lang3.StringUtils.isEmpty(ftime)) {
            ftime = dto.getTime();
        }
        if (org.apache.commons.lang3.StringUtils.isEmpty(ftime)) {
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date ftime_d = sdf.parse(ftime);
            long gapTime = System.currentTimeMillis() - ftime_d.getTime();
            long gapHour = gapTime / 1000 / 3600;
            if (gapHour >= Long.valueOf(expressStatusThreshold).longValue()) {
                return true;
            }
        } catch (ParseException e) {
            log.error("===时间转换异常==={}", e);
        }
        return false;
    }

    private void pushOne(String json, long delayTimes) {
        // 给延迟队列发送消息
        rabbitTemplate.convertAndSend(QueueConstants.ORDER_STATE_ONE, json, message -> {
            //给消息设置延迟毫秒值
            message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
            return message;
        });
    }

    private void pushTwo(String json, long delayTimes) {
        // 给延迟队列发送消息
        rabbitTemplate.convertAndSend(QueueConstants.LOGISTICS_MESSAGE, json, message -> {
            //给消息设置延迟毫秒值
            message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
            return message;
        });
    }


//    public void examineOrdersExpressStatus() {
//        List<BankerOrder> bankerOrderList = bankerOrderDao.queryBankerOrderListBy48Hour();
//        bankerOrderList.parallelStream().forEach(item -> {
//            // 如果快递号为null 加入异常
//            if (StringUtil.isEmpty(item.getExpressNo())) {
//                saveExceptionOrder(item, "未录入快递单号");
//                updateBankerOrderStatus(item, 2, "");
//                return;
//            }
//            // 如果快递号不为null 查询快递
//            QueryTrack queryTrack = new QueryTrack();
//            QueryTrackReq queryTrackReq = new QueryTrackReq();
//            QueryTrackParam queryTrackParam = new QueryTrackParam();
//            queryTrackParam.setCom(item.getExpressCode());
//            queryTrackParam.setNum(item.getExpressNo());
//            queryTrackParam.setPhone(item.getUserTel());
//            queryTrackReq.setParam(queryTrackParam);
//            queryTrackReq.setCustomer(PropertiesReader.get("customer"));
//            queryTrackReq.setSign(SignUtils.sign(new Gson().toJson(queryTrackParam) + PropertiesReader.get("key") + PropertiesReader.get("customer")));
//            QueryTrackResp resp = queryTrack.queryTrack(queryTrackReq);
//            if ("500".equals(resp.getReturnCode()) || "400".equals(resp.getReturnCode())) {
//                saveExceptionOrder(item, "查无快递单号");
//                updateBankerOrderStatus(item, 2, JSONObject.toJSONString(resp));
//            } else {
//                if ("200".equals(resp.getStatus())) {
//                    // 查询成功
//                    List<QueryTrackData> list = resp.getData();
//                    if (list.size() <= 1) {
//                        QueryTrackData queryTrackData = list.get(0);
//                        if (queryTrackData.getContext().contains("揽收")) {
//                            saveExceptionOrder(item, "快递一直属于揽收状态");
//                            updateBankerOrderStatus(item, 2, JSONObject.toJSONString(list));
//                        } else {
//                            updateBankerOrderStatus(item, 3, JSONObject.toJSONString(list));
//                        }
//                    } else {
//                        updateBankerOrderStatus(item, 3, JSONObject.toJSONString(list));
//                    }
//                }
//            }
//        });
//    }

    /**
     * 保存异常订单
     *
     * @param order
     * @param desc
     */
//    @Transactional(rollbackFor = Exception.class)
//    public void saveExceptionOrder(BankerOrder order, String desc) {
//        OrderException orderException = null;
//        orderException = orderExceptionMapper.selectById(order.getId());
//        int flag = 1;
//        if (null == orderException) {
//            orderException = new OrderException();
//            flag = 0;
//        }
//        Byte oldStatus = orderException.getStatus();
//        BeanUtils.copyProperties(order, orderException);
//        orderException.setExceptionDesc(desc);
//        if (null != order.getBankerId()) {
//            Banker banker = bankerMapper.selectByPrimaryKey(order.getBankerId());
//            orderException.setBankerName(banker.getName());
//        }
//        orderException.setOrderOn(order.getOrderNo());
//        orderException.setOrderCreateTime(order.getCreateTime());
//        orderException.setCreateTime(new Date());
//        orderException.setUpdateTime(new Date());
//        try {
//            if (0 == flag) {
//                orderException.setStatus((byte) 1);
//                orderExceptionMapper.insertSelective(orderException);
//            } else {
//                orderException.setStatus(oldStatus);
//                if ("快递停留过长".equals(desc)) {
//                    orderException.setStatus((byte) 1);
//                }
//                orderExceptionMapper.updateByPrimaryKeySelective(orderException);
//            }
//        } catch (Exception e) {
//            log.error("*********************{}", e);
//        }
//    }


    /**
     * 更新订单状态
     *
     * @param order
     * @param status 1 无状态 2 异常 3 正常
     * @param res
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBankerOrderStatus(BankerOrder order, Integer status, String res) {
        order.setStatus(status.byteValue());
        order.setExpressRecord(res);
        bankerOrderMapper.updateByPrimaryKeySelective(order);
    }

    public void examineOrdersExpressStatus2() {
        List<Map<String, String>> bankerOrderList = bankerOrderDao.queryBankerOrderList();
        bankerOrderList.stream().forEach(item -> {

            String com = item.get("com");
            String track = item.get("track");
            String phone = item.get("phone");
            // 如果快递号不为null 查询快递
            QueryTrack queryTrack = new QueryTrack();
            QueryTrackReq queryTrackReq = new QueryTrackReq();
            QueryTrackParam queryTrackParam = new QueryTrackParam();
            queryTrackParam.setCom(com);
            queryTrackParam.setNum(track);
            queryTrackParam.setPhone(phone);
            queryTrackReq.setParam(queryTrackParam);
            queryTrackReq.setCustomer(PropertiesReader.get("customer"));
            queryTrackReq.setSign(SignUtils.sign(new Gson().toJson(queryTrackParam) + PropertiesReader.get("key") + PropertiesReader.get("customer")));
            QueryTrackResp resp = queryTrack.queryTrack(queryTrackReq);
            log.info("快递100 手动查询结果：{}", JSONObject.toJSONString(resp));
            if ("500".equals(resp.getReturnCode()) || "400".equals(resp.getReturnCode())) {
                bankerOrderDao.updateOrdersStatus(String.valueOf(item.get("id")), "查无快递单", JSONObject.toJSONString(resp), 1);
            } else {
                if ("200".equals(resp.getStatus())) {
                    // 查询成功
                    List<QueryTrackData> list = resp.getData();
                    if (list.size() <= 1) {
                        QueryTrackData queryTrackData = list.get(0);
                        if (queryTrackData.getContext().contains("揽收")) {
                            bankerOrderDao.updateOrdersStatus(String.valueOf(item.get("id")), "快递一直属于揽收状态", JSONObject.toJSONString(list), 1);
                        } else {
                            bankerOrderDao.updateOrdersStatus(String.valueOf(item.get("id")), "快递一直属于揽收状态", JSONObject.toJSONString(list), 2);
                        }
                    } else {
                        bankerOrderDao.updateOrdersStatus(String.valueOf(item.get("id")), "快递一直属于揽收状态", JSONObject.toJSONString(list), 2);

                    }
                    if (list.size() <= 1) {
                        QueryTrackData queryTrackData = list.get(0);
                        if (queryTrackData.getContext().contains("揽收")) {
                        }
                    }
                }
            }
        });
    }

    public void sendMessageInMinutes() {
        String time = sysConfigUtil.getSysConfig("ORDER_MESSAGE_TIME");
        Integer times = Integer.valueOf(time);
        // 获取需要发送的电话(n分钟内）
        List<OrderMsgResponse> orderPhoneList = ordersDao.getOrderPhoneList(times);
        orderPhoneList.stream()
                .forEach(item -> {
                    // 查询该号码24小时内是否发送过短信
                    String result = redisService.get(RedisConstants.ORDER_TEL + item.getTel());
                    if (StringUtils.isEmpty(result)) {
                        String id = Integer.toHexString(item.getId());
                        SendMsg.sendOrderInfoMsg(item.getTel(), "yitanjj.com/" + id);
                        redisService.set(RedisConstants.ORDER_ID + id, item.getId() + "");
                        redisService.expire(RedisConstants.ORDER_ID + id, ExpireTimeConstant.EXPIRE_24_HOURS);
                        // 过期时间
                        redisService.set(RedisConstants.ORDER_TEL + item.getTel(), item.getId() + "");
                        redisService.expire(RedisConstants.ORDER_TEL + item.getTel(), ExpireTimeConstant.EXPIRE_24_HOURS);
                    }
                    ordersInfoDao.updateMessage(item.getId());
                });
    }

    public Integer queryByOrderNo(String orderNo) {
        return ordersDao.selectByOrderNo(orderNo);
    }

    /**
     * 当前时间30分钟以内的已支付订单集合
     *
     * @return
     */
    public List<Orders> queryCurTimeBefore30MinIsPayOrders(Date beforeDate, Date curDate) {
        OrdersExample example = new OrdersExample();
        example.createCriteria().andPayTimeBetween(beforeDate, curDate).andIsPayEqualTo((byte) 1);
        List<Orders> ordersList = ordersMapper.selectByExample(example);
        return ordersList;
    }

    /**
     * 当前时间30分钟内创建的订单集合
     *
     * @param beforeDate
     * @return
     */
    public List<Orders> queryCurTimeBefore30MinCreateOrders(Date beforeDate, Date curDate) {
        OrdersExample example = new OrdersExample();
        example.createCriteria().andCreateTimeBetween(beforeDate, curDate);
        List<Orders> ordersList = ordersMapper.selectByExample(example);
        return ordersList;
    }

    public void deleteByOrderNo(String orderNo) {
        ordersMapper.deleteByOrderNo(orderNo);
    }

    public Orders selectOrderByNo(String orderNo) {
        return ordersDao.selectOrderByNo(orderNo);
    }

    public void giveBrokerageByDynamic() {
        //查询收货时间为今天的订单详情
        List<OrderResp> list = ordersDao.queryOrdersByOrderNo();
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(item -> {
                log.info("======开始赠送佣金===={}", item.getOrderId());
                Integer dynamicId = item.getDynamicId();
                Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dynamicId);
                if (dynamic == null) {
                    return;
                }
                if (null == dynamic.getIsReason()) {
                    dynamic.setIsReason((byte) 1);
                }
                if (0 == dynamic.getIsReason() || 1 != dynamic.getStatus()) {
                    return;
                }
                if (ActivityTypeEnums.ZERO_EVALUATION.name().equals(dynamic.getActivityType())) {
                    return;
                }
                BigDecimal productPrice = dynamic.getProdcutPrice();//商品售价
                BigDecimal brokerage = productPrice.multiply(new BigDecimal(brokerageRatio)).setScale(4, RoundingMode.HALF_UP).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                usersClient.addBalance(brokerage, dynamic.getUserId(), UserBalanceSourceEnums.EVALUATION_COMMISSION.name());
                //修改赠送标识
                ordersDao.updateFlag(item.getOrderId());
                log.info("======结束赠送佣金===={}", item.getOrderId());
            });
        }
    }

    public void findOrderAllByStatus() {
        List<com.ytjj.quartz.model.OrdersInfo> byStatus = ordersDao.findOrderAllByStatus();
        long bindingHours = 12 * 24 * 60 * 60 * 1000; // 规定12天
        long date = new Date().getTime(); // 当前时间
        byStatus.stream().forEach(item -> {
            if (null == item.getDeliveryTime()) {
                return;
            }
            long deliveryTime = item.getDeliveryTime().getTime(); // 发货时间
            if (date - deliveryTime >= bindingHours) {
                item.setReceiveTime(new Date());
                ordersDao.updateStatus(item);//修改订单详情状态
                OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
                ordersInfoExample.createCriteria().andOrderIdEqualTo(item.getOrderId());
                List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
                //修改主订单
                if (ordersInfos.size() > 0 && ordersInfos.size() < 2) {
                    Orders orders = new Orders();
                    orders.setOrderStatus("3");
                    orders.setId(item.getOrderId());
                    ordersMapper.updateByPrimaryKeySelective(orders);
                } else {
                    if (!CollectionUtils.isEmpty(ordersInfos)) {
                        int index = 0;
                        for (OrdersInfo info : ordersInfos) {
                            if (info.getOrderinfoStatus().equals("3")) {
                                index += 1;
                            }
                        }
                        if (index == ordersInfos.size()) {
                            Orders order = new Orders();
                            order.setOrderStatus("3");
                            order.setId(item.getOrderId());
                            ordersMapper.updateByPrimaryKeySelective(order);
                        }
                    }
                }
            }
        });
    }

    public static void main(String[] args) {
        long bindingHours = 12 * 24 * 60 * 60 * 1000;
        long date = new Date().getTime();
        long result = date - bindingHours;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(result);

        System.out.println("bindingHours:" + bindingHours);
        System.out.println("date:" + date);
        System.out.println("result:" + result);
        System.out.println("时间:" + format);

    }

    public void cancelOrder() {
        List<Orders> orderList = ordersDao.selectByNoIsPay();
        //todo 目前订单购买的商品数量只有1
        final Integer sum = 1;
        if (!CollectionUtils.isEmpty(orderList)) {
            orderList.stream().forEach(orders -> {
                log.info("==========取消订单========={}", orders.getId());
                //修改订单状态为已关闭
                orders.setOrderStatus(OrderStatusEnums.CLOSED.getValue());
                orders.setOrderRemarks("订单超时未支付,已取消");
                Integer flag = ordersMapper.cancelOrderByParams(orders, 0);
                if (flag > 0) {
                    //修改订单详情为已关闭
                    OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
                    ordersInfoExample.createCriteria().andOrderIdEqualTo(orders.getId());
                    List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
                    ordersInfos.stream().forEach(item -> {
                        item.setOrderinfoStatus(OrderStatusEnums.CLOSED.getValue());
                        item.setCloseRemarks("订单超时未支付,已取消");
                        ordersInfoMapper.updateByPrimaryKeySelective(item);
                        Product product = productMapper.selectByPrimaryKey(item.getProductId());
                        //一分兑 减少兑换次数
                        if (product.getActivityType().equals("PENNY_CONVERSION")) {
                            String s = redisService.get(com.ytjj.common.constants.RedisConstants.GUOB_H5_SIGN_CONVERSION + TokenUtil.getToken());
                            if (org.apache.commons.lang3.StringUtils.isNotBlank(s)) {
                                int i = Integer.parseInt(s);
                                int count = i + 1;
                                redisService.set(com.ytjj.common.constants.RedisConstants.GUOB_H5_SIGN_CONVERSION + TokenUtil.getToken(), Integer.toString(count));
                            }
                        }
                        //库存解冻
                        try {
                            //更新库存冻结状态(调用这个方法后 还需要调用下面的subAndAddStock方法)
                            updateProductStock(item.getChildOrderNo(), 4);
                        } catch (Exception e) {
                            log.error("========更新库存冻结状态========orders.getOrderNo()====={}", orders.getOrderNo());
                        }

                        //同步支付宝订单数据
                        try{
                            OrdersPayResponse ordersPay = ordersPayMapper.queryByChildOrderNo(item.getChildOrderNo());
                            if (!org.springframework.util.StringUtils.isEmpty(ordersPay.getTradeType()) && "aliPay-jsApi".equals(ordersPay.getTradeType())) {
                                AliPayOrderSyncRequest request = new AliPayOrderSyncRequest();
                                request.setCreateTime(ordersPay.getOrderCreateTime());
                                request.setOrderId(ordersPay.getOrderId().toString());
                                request.setOrderStatus("CLOSED");
                                request.setUserId(ordersPay.getUserId());
                                request.setChildId(ordersPay.getChildId());
                                request.setProductName(ordersPay.getProductName());
                                request.setProductImg(ordersPay.getProductImg());
                                request.setOrderNo(ordersPay.getOrderNo());
                                mallClient.syncAliPayOrder(request);
                            }
                        }catch (Exception e) {
                            log.error("同步支付订单状态失败：{}",e.getMessage());
                        }


//                     //加库存 减销量
//                    Product product = productMapper.selectByPrimaryKey(item.getProductId());
//                    if (product.getIsZeroProduct() != null && product.getIsZeroProduct() == 1 && product.getStockEvaluation() != null && product.getStockEvaluation() > 0) {
//                        product.setStockEvaluation(product.getStockEvaluation() + sum);
//                    } else {
//                        product.setStock(Optional.ofNullable(product.getStock()).orElse(0) + sum);
//                    }
//                    productMapper.updateByPrimaryKeySelective(product);
//                    ProductSpec productSpec = productSpecMapper.selectByPrimaryKey(item.getProductSpecId());
//                    productSpec.setBuySum(Optional.ofNullable(productSpec.getBuySum()).orElse(0) - sum);
//                    productSpec.setStock(Optional.ofNullable(productSpec.getStock()).orElse(0) + sum);
//                    productSpecMapper.updateByPrimaryKeySelective(productSpec);
                    });
                }
            });
        }
    }

    /**
     * 更新库存冻结状态(调用这个方法后 还需要调用下面的subAndAddStock方法)
     *
     * @param orderNo 订单编号
     * @param status  更新状态值 2-已扣库存 3-退还库存 4-冻结作废
     */
    public void updateProductStock(String orderNo, Integer status) {
        log.info("========更新库存冻结状态--超时未支付========orderNo====={}", orderNo);
        Map<String, String> map = new LinkedMap();
        map.put("orderNo", orderNo);
        map.put("status", String.valueOf(status));
        HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/stock/updateProductStock", map, supplyApiConfig.getHeadsMap());
    }

    ThreadPoolExecutor pools = new ThreadPoolExecutor(5, 10, 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024));

    /**
     * 查询一个月内的订单,获取供应链订单信息对比修改
     * type 1：  30天前的单；其他： 30天内的
     */
    public void checkSupplyChainOrder(Integer type) {
        List<OrdersInfo> ordersInfoList = new ArrayList<>();
        //30天之前的
        if(null != type && type == 1){
            ordersInfoList = ordersInfoMapper.selectBetween(unfilledOrderDay);
        }else{//30天内的
            ordersInfoList = ordersInfoMapper.select(unfilledOrderDay);
        }
        if (CollectionUtils.isEmpty(ordersInfoList)) {
            return;
        }
        List<String> childOrderNo = ordersInfoList.stream().map(OrdersInfo::getChildOrderNo).collect(Collectors.toList());
        List<OrderQueryResponse> orderQueryResponses = querySupplyChainOrderInfo(childOrderNo);
        List<String> sendMsgChildOrderNoList = new ArrayList<>();
        for (OrdersInfo ordersInfo : ordersInfoList) {
            List<OrderQueryResponse> orderQueryResponse = orderQueryResponses.stream().filter(item -> item.getChildOrderNo().equals(ordersInfo.getChildOrderNo())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(orderQueryResponse)) {
                OrderQueryResponse response = orderQueryResponse.get(0);
                if ("1".equals(ordersInfo.getOrderinfoStatus()) && response.getOrderInfoStatus()==2) {
                    //todo 发短信
                    sendMsgChildOrderNoList.add(ordersInfo.getChildOrderNo());
                }
                Boolean flag = false;
                if (null != response.getOrderInfoStatus() && !String.valueOf(response.getOrderInfoStatus()).equals(ordersInfo.getOrderinfoStatus())) {
                    ordersInfo.setOrderinfoStatus(response.getOrderInfoStatus().toString());
                    flag = true;
                }
                if (StringUtils.isNotBlank(response.getExpressNo()) && !response.getExpressNo().equals(ordersInfo.getExpressNo())) {
                    ordersInfo.setExpressNo(response.getExpressNo());
                    flag = true;
                }
                if (StringUtils.isNotBlank(response.getExpressCode()) && !response.getExpressCode().equals(ordersInfo.getExpressCompanyNo())) {
                    ordersInfo.setExpressCompanyNo(response.getExpressCode());
                    flag = true;
                }
                if(flag){
                    if (null != response.getImportTime() && response.getImportTime() != ordersInfo.getDeliveryTime()) {
                        ordersInfo.setDeliveryTime(response.getImportTime());
                    }
                    if (null != response.getIsExport() && !ordersInfo.getIsExport().equals(response.getIsExport())) {
                        ordersInfo.setIsExport(response.getIsExport());
                    }
                    if (null != response.getExportTime() && ordersInfo.getCheackTime() != response.getExportTime()) {
                        ordersInfo.setCheackTime(response.getExportTime());
                    }
                    if (null != response.getFinishedTime()) {
                        ordersInfo.setFinishedTime(response.getFinishedTime());
                    }
                    if (null != response.getOrderInfoStatus() && response.getOrderInfoStatus() == 3) {
                        //签收时间
                        if(null != response.getReceiveTime()){
                            ordersInfo.setReceiveTime(response.getReceiveTime());
                        }else {
                            ordersInfo.setReceiveTime(new Date());
                        }
                        //同步支付宝订单状态（）;
                        try{
                            OrdersPayResponse ordersPay = ordersPayMapper.queryByChildOrderNo(ordersInfo.getChildOrderNo());
                            if (!org.springframework.util.StringUtils.isEmpty(ordersPay.getTradeType()) && "aliPay-jsApi".equals(ordersPay.getTradeType())) {
                                AliPayOrderSyncRequest request = new AliPayOrderSyncRequest();
                                request.setCreateTime(ordersPay.getOrderCreateTime());
                                request.setOrderId(ordersPay.getOrderId().toString());
                                request.setOrderStatus("FINISHED");
                                request.setUserId(ordersPay.getUserId());
                                request.setChildId(ordersPay.getChildId());
                                request.setProductName(ordersPay.getProductName());
                                request.setProductImg(ordersPay.getProductImg());
                                request.setOrderNo(ordersPay.getOrderNo());
                                mallClient.syncAliPayOrder(request);
                            }
                        }catch (Exception e) {
                            log.error("同步支付订单状态失败：{}",e.getMessage());
                        }

                    }
                    Integer status = ordersInfoMapper.selectStatusById(ordersInfo.getChildOrderNo());
                    //避免销售端的订单非售后状态，被供应链的售后状态覆盖。供应链是不能发起售后的。
                    if (status != 6 && response.getOrderInfoStatus() != 6){
                        ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
                        //修改主订单状态
                        List<OrdersInfo> ordersInfos = ordersDao.getAllOrdersInfoByOrderId(ordersInfo.getOrderId());
                        if (!CollectionUtils.isEmpty(ordersInfos)) {
                            int index = 0;
                            for (OrdersInfo info : ordersInfos) {
                                if (info.getOrderinfoStatus().equals(ordersInfo.getOrderinfoStatus())) {
                                    index += 1;
                                }
                            }
                            if (index == ordersInfos.size()) {
                                Orders order = new Orders();
                                order.setOrderStatus(ordersInfo.getOrderinfoStatus());
                                OrdersExample ordersExample = new OrdersExample();
                                ordersExample.createCriteria()
                                        .andIdEqualTo(ordersInfo.getOrderId());
                                ordersMapper.updateByExampleSelective(order, ordersExample);
                            }
                        }
                    }
                }
            }
        }
        try {
            if ("1".equals(expressSmsFlag)) {
                deliverGoodsSendMsg(sendMsgChildOrderNoList);
            }
        } catch (Exception e) {
            log.info("===发送发货短信异常==={}", e);
        }
    }

    /**
     * 去重获取订单信息
     * @param childOrderNoList
     */
    private void deliverGoodsSendMsg(List<String> childOrderNoList) {
        if (CollectionUtils.isEmpty(childOrderNoList)) {
            return;
        }
        List<OrdersInfo> ordersInfoList = ordersInfoMapper.selectByChildOrderNoList(childOrderNoList);
        //根据快递公司编码 + 快递单号 去重
        List<OrdersInfo> filterList = ordersInfoList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() ->
                                new TreeSet<>(Comparator.comparing(userOrder -> userOrder.getExpressCompanyNo() + userOrder.getExpressNo()))),
                        ArrayList::new ));

        filterList.stream().forEach(item -> {
            Orders orders = ordersMapper.selectByPrimaryKey(item.getOrderId());
            String tel = orders.getTel();
            String productName = item.getProductName();
            List<OrdersInfo> details = ordersInfoList.stream().filter(ordersInfo ->
                    ordersInfo.getExpressCompanyNo().equals(item.getExpressCompanyNo())
                            && ordersInfo.getExpressNo().equals(item.getExpressNo())).collect(Collectors.toList());
            if (productName.length() > 12) {
                productName = productName.substring(0, 12) + "-";
            }else {
                if (!CollectionUtils.isEmpty(details) && details.size() > 1) {
                    productName = productName + "-";
                }
            }

            String expressCompany = ExpressDicUtil.getKey(item.getExpressCompanyNo());

            log.info("===订单：{}已发货，接收短信手机号{}，发送到MQ===",orders.getOrderNo(),tel);
            SmsDto smsDto = new SmsDto();
            smsDto.setPhone(tel);
            smsDto.setType(6);
            smsDto.setCode(productName);
            smsDto.setExpressNo(item.getExpressNo());
            smsDto.setExpressCompany(expressCompany);
            smsDto.setToken(orders.getH5Token());
            smsDto.setOrderSource(orders.getOrderSource());
            smsDto.setChannel(orders.getChannel());
            smsDto.setDomainUrl(orders.getDomainUrl());
            rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, smsDto);
        });
    }

    /**
     * 查询订单信息
     * 主要查询物流信息（物流公司编码、快递单号、发货时间、是否导出、导出时间）
     */
    public List<OrderQueryResponse> querySupplyChainOrderInfo(List<String> childOrderNo) {
        OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
        orderQueryRequest.setChildOrderNo(childOrderNo);
        String json = com.gexin.fastjson.JSON.toJSONString(orderQueryRequest);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/query", json, supplyApiConfig.getHeadsMap());
        if (org.springframework.util.StringUtils.isEmpty(resultJson)) {
            return new ArrayList<>();
        }
        JSONObject parse = JSON.parseObject(resultJson);
        List<OrderQueryResponse> orderQueryResponses = JSONObject.parseArray(parse.getString("data"), OrderQueryResponse.class);
        return orderQueryResponses;
    }


    public void updateSupplyChainOrder() {
        List<OrdersInfo> ordersInfoList = ordersInfoMapper.selectByAfterType();
        if (CollectionUtils.isEmpty(ordersInfoList)) {
            return;
        }
        List<String> childOrderNo = ordersInfoList.stream().map(OrdersInfo::getChildOrderNo).collect(Collectors.toList());
        List<OrderQueryResponse> orderQueryResponses = querySupplyChainOrderInfo(childOrderNo);
        for (OrdersInfo ordersInfo : ordersInfoList) {
            List<OrderQueryResponse> orderQueryResponse = orderQueryResponses.stream().filter(item -> item.getChildOrderNo().equals(ordersInfo.getChildOrderNo())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(orderQueryResponse)) {
                OrderQueryResponse response = orderQueryResponse.get(0);
                if (null != response.getOrderInfoStatus()) {
                    //是否需要更新标志
                    Boolean flag = false;
                    OrdersInfo ordersInfoEntity = new OrdersInfo();
                    ordersInfoEntity.setId(ordersInfo.getId());
                    if (StringUtils.isNotBlank(response.getExpressNo()) && !response.getExpressNo().equals(ordersInfo.getExpressNo())) {
                        ordersInfoEntity.setExpressNo(response.getExpressNo());
                        flag = true;
                    }
                    if (StringUtils.isNotBlank(response.getExpressCode()) && !response.getExpressCode().equals(ordersInfo.getExpressCompanyNo())) {
                        ordersInfoEntity.setExpressCompanyNo(response.getExpressCode());
                        flag = true;
                    }
                    if (null != response.getImportTime() && response.getImportTime() != ordersInfo.getDeliveryTime()) {
                        ordersInfoEntity.setDeliveryTime(response.getImportTime());
                        flag = true;
                    }
                    if (null != response.getIsExport() && !ordersInfo.getIsExport().equals(response.getIsExport())) {
                        ordersInfoEntity.setIsExport(response.getIsExport());
                        flag = true;
                    }
                    if (null != response.getExportTime() && ordersInfo.getCheackTime() != response.getExportTime()) {
                        ordersInfoEntity.setCheackTime(response.getExportTime());
                        flag = true;
                    }
                    if (null != response.getOrderInfoStatus() && response.getOrderInfoStatus() == 3) {
                        if(null != response.getReceiveTime()){
                            ordersInfoEntity.setReceiveTime(response.getReceiveTime());
                        }else {
                            ordersInfoEntity.setReceiveTime(new Date());
                        }
                        flag = true;
                    }
                    //修改子订单数据
                    if(flag){
                        ordersInfoMapper.updateByPrimaryKeySelective(ordersInfoEntity);
                    }
                }
            }
        }
    }

    public void checkIsPayOrder() {
        List<String> childOrderNoList = ordersInfoDao.selectIsPayOrder();
        if (CollectionUtils.isEmpty(childOrderNoList)){
            return;
        }
        OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
        orderQueryRequest.setChildOrderNo(childOrderNoList);
        String json = com.gexin.fastjson.JSON.toJSONString(orderQueryRequest);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/selectByChildOrderNo", json, supplyApiConfig.getHeadsMap());
        log.info("=========销售端存在供应链不存在的订单===========childOrderNo:{}",resultJson);
        if (null != resultJson){
            List<String> list = JSONObject.parseArray(resultJson, String.class);
            list.stream().forEach(item ->{
                Integer orderId = ordersInfoDao.selectByChildOrderNo(item);
                mallClient.ordersUpload(orderId);
            });
        }
    }

    public void checkIsPayOrderBy1Day() {
        List<String> childOrderNoList = ordersInfoDao.selectIsPayOrderBy1Day();
        if (CollectionUtils.isEmpty(childOrderNoList)){
            return;
        }
        OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
        orderQueryRequest.setChildOrderNo(childOrderNoList);
        String json = com.gexin.fastjson.JSON.toJSONString(orderQueryRequest);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/selectByChildOrderNo", json, supplyApiConfig.getHeadsMap());
        log.info("=========销售端存在供应链不存在的订单===========childOrderNo:{}",resultJson);
        if (null != resultJson){
            List<String> list = JSONObject.parseArray(resultJson, String.class);
            list.stream().forEach(item ->{
                Integer orderId = ordersInfoDao.selectByChildOrderNo(item);
                mallClient.ordersUpload(orderId);
            });
        }
    }

    public void uploadOrderToSupply() {
        List<String> childOrderNoList = ordersInfoDao.uploadOrderToSupplyByEveryday();
        if (CollectionUtils.isEmpty(childOrderNoList)) {
            return;
        }
        childOrderNoList.stream().forEach(item -> {
            Integer orderId = ordersInfoDao.selectByChildOrderNo(item);
            mallClient.ordersUpload(orderId);
        });
    }

    /**
     * 查询10分钟内重复支付的订单
     * @return
     */
    public List<String> selectRepeatPayOrderNos() {
        List<RepeatPayOrderRecordDto> repeatPayOrderRecordDtos = ordersInfoDao.queryRepeatPayOrder();
        if (CollectionUtils.isEmpty(repeatPayOrderRecordDtos)) {
            return null;
        }
        return repeatPayOrderRecordDtos.stream().map(RepeatPayOrderRecordDto::getOrderNo).collect(Collectors.toList());
    }

    /**
     * 查询实际支付成功，但是订单表状态为超时未支付的订单
     * @return
     */
    public List<String> selectRelPayIsSuccessButOrderStatusIsTimeout() {
        List<String> error_orders = ordersInfoDao.queryRelPayIsSuccessButOrderIsTimeout();
        if (CollectionUtils.isEmpty(error_orders)) {
            return null;
        }
        if (!CollectionUtils.isEmpty(error_orders)) {
            try {
                //订单状态作修正
                int size = ordersInfoDao.revisePayIsSuccessButOrderIsNoPay(error_orders);
                log.info("===revisePayIsSuccessBuyOrderIsNoPay.size={},{}", size, error_orders.size());
            } catch (Exception e) {
                log.error("===revisePayIsSuccessBuyOrderIsNoPay is error==={}", e);
            }

        }
        return error_orders;
    }

    /**
     * 退款后订单状态异常的订单
     * @return
     */
    public List<String> refundAfterOrderStatusError() {
        List<String> error_orderIds = ordersInfoDao.refundAfterOrderStatusError();
        if (CollectionUtils.isEmpty(error_orderIds)) {
            return null;
        }
        return error_orderIds;
    }

    /**
     * 根据已支付但被关闭的情况更新
     */
    @Transactional(rollbackFor = Exception.class)
    public void dealOrdersByPaySuccess(Orders order) {
        List<OrdersInfo> ordersInfos = ordersInfoMapper.selectOrderInfoByOrderId(order.getId());
        for (OrdersInfo oi : ordersInfos) {
            ReturnGoodsExample returnGoodsExample = new ReturnGoodsExample();
            returnGoodsExample.createCriteria().andOrdersInfoIdEqualTo(oi.getId());
            long count = returnGoodsMapper.countByExample(returnGoodsExample);
            if (count > 0) {
                return;
            }
        }
        //更新主订单
        Orders newOrder = new Orders();
        newOrder.setOrderStatus(OrderStatusEnums.UNSHIPPED.getValue());
        newOrder.setIsPay(IsPayConstant.YES);
        newOrder.setTradeNo(order.getTradeNo());
        newOrder.setOrderRemarks("订单已修复为已支付");
        //更新条件
        OrdersExample ordersExample = new OrdersExample();
        ordersExample.createCriteria().andIdEqualTo(order.getId()).andIsRefundEqualTo(0).andIsPayEqualTo(IsPayConstant.NO);
        int orderFlag = ordersMapper.updateByExampleSelective(newOrder, ordersExample);

        //更新子订单
        if (orderFlag > 0) {
            OrdersInfo ordersInfo = new OrdersInfo();
            ordersInfo.setOrderinfoStatus(OrderStatusEnums.UNSHIPPED.getValue());
            ordersInfo.setCloseRemarks("订单已修复为已支付");
            OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
            ordersInfoExample.createCriteria().andOrderIdEqualTo(order.getId());
            ordersInfoMapper.updateByExampleSelective(ordersInfo, ordersInfoExample);
            String msg = String.format("======订单支付了但被关闭,已修复成支付状态！主订单：%s,支付单号：%s，====",order.getOrderNo(),order.getTradeNo());
            log.info(msg);
            FeiShuUtil.sendMsg(msg);
        }
    }

    public void checkIsPayOrderCount(int minute){
        if(checkOrderFeishu){
            int count = ordersMapper.checkIsPayOrderCount(minute);
            if (count==0){
                FeiShuUtil.sendMsg(String.format("最近%s分钟没有产生支付订单 大家赶紧检查下系统能否正常下单",minute));
            }
        }
    }


    public void checkOrdersAddress(int minute) {
        List<Orders> orders =  ordersMapper.checkOrdersAddress(minute);
        if (!CollectionUtils.isEmpty(orders)) {
            for (Orders order : orders) {
                int provinceCount = StringUtils.countMatches(order.getUserAddress(), "省");
                int cityCount = StringUtils.countMatches(order.getUserAddress(), "市");
                String userAddress = order.getUserAddress();
                boolean flag =true;
                if (userAddress.contains("北京市")||userAddress.contains("天津市") ||userAddress.contains("重庆市") || userAddress.contains("上海市")) {
                    if (provinceCount<=2 || cityCount<=2) {
                        flag = false;
                    }

                }

                if (flag && (provinceCount>=2 || cityCount>=2)) {
                    List<OrdersInfo> ordersInfos = ordersInfoMapper.selectOrderInfoByOrderId(order.getId());
                    if (!CollectionUtils.isEmpty(ordersInfos)) {
                        FeiShuUtil.sendDzMsg(String.format("请注意!!!  订单号为:%s的订单,收货人手机号为%s,收货地址为:%s ===,包含多个省或多个市",
                                ordersInfos.get(0).getChildOrderNo(),order.getTel(),order.getUserAddress()));
                    }

                }
            }
        }
    }

    public void updateErrorOrderRemark() {
        List<Orders> orders = ordersMapper.queryErrorOrderRemarkOrder();
        if (!CollectionUtils.isEmpty(orders)) {
            List<Integer> orderIds = orders.stream().map(Orders::getId).collect(Collectors.toList());
            ordersMapper.updateErrorOrderRemark(orderIds);
            ordersInfoMapper.updateErrorOrderRemark(orderIds);
        }
    }
}
